import {uuid} from 'util/uuid'
import {register,login,getUserInfo,logout} from 'http'
const OK = 200
export default {
    state:{
        uuid:uuid(),
        userInfo:{}
    },
    getters:{},
    mutations:{
        login(state,userInfo){
            state.userInfo = userInfo
        }
    },
    actions:{
        //登录
        async login({commit},{phone,password}){
            try {
                const {code,data,message} = await login(phone,password)
                if(code === OK){
                    commit('login',data)
                    //登录成功要把token 存到本地储存
                    localStorage.setItem('login_token',data.token)                  
                }
                //code是啥都返回出去
                return {code,data,message}
            } catch (error) {
                throw  new Error(error)
            }
                
        },
        //注册
        async register(store,{phone,password,registerCode}){
            try {
                const {code,data,message} = await register(phone,password,registerCode)
                return {code,data,message}
            } catch (error) {
                throw  new Error(error)
            }
        },
        //自动登录
        async getUserInfo({commit}){
            try {
                const {code,data} = await getUserInfo()
                //登录成功,覆盖userInfo
                if(code === OK){
                    commit('login',data)
                }
                return code
            } catch (error) {
                throw  new Error(error)
            }
        },
        //退出
        async logout({commit}){
            try {
                const {code} = await logout()
                 //退出,将userInfo清空
                if(code === OK){
                    commit('login','')
                    //清除存储在本地的token
                    localStorage.removeItem('login_token')
                }
                return code
            } catch (error) {
                throw  new Error(error)
            }
        }

    }
}